<template>
  <div  class="service" style="height: 100%;">
    <div class="app-container-inner" style="display: flex;flex-direction: column;flex: 1;" v-loading="tableLoading" element-loading-text="加载中...">
      <div class="header">
      <div class=" btn_btn">
        <button class="btn btn-bg mr5" @click="syncclick">同步页面数据
        </button>
        <!-- <el-dropdown trigger="click">
          <el-button class="btn btn-bg5 mr5 btn-change" :disabled="disabledBatchBtn"
            :style="'cursor:' + (disabledBatchBtn ? 'not-allowed; color: #aaaaaa; border-color: #aaaaaa;' : '')">
            <img :src="batch" class="mr5" alt="" sizes="16" srcset="" />批量操作
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>批量禁用
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown> -->
      </div>

      <!-- 关键词搜索 -->
      <div class="search">
        <el-form :model="servicePageSearch" :inline="true">
          <!-- <el-form-item>
            <el-select class="el-select mr5" v-model="servicePageSearch.type" placeholder="页面类型" filterable clearable>
              <el-option v-for="item in pageTypeOption" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-input class="input-with-select mr5" v-model="servicePageSearch.name" placeholder="页面名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-input class="input-with-select mr5" v-model="servicePageSearch.title" placeholder="页面标题" clearable />
          </el-form-item>
          <el-form-item>
            <el-button class="btn-with-select btn bgColor1" :icon="Search" @click="getList">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 列表表格 -->
    <div class="table">
      <el-table  border stripe resizable :data="tableData"
        ref="tableDom" @selection-change="handleChange" style="position: absolute;" height="100%">
        <el-table-column type="selection" width="50" fixed />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="name" label="页面名称" width="160" />
        <el-table-column prop="type" label="页面类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 1" type="success">客户报单端</el-tag>
            <el-tag v-else-if="scope.row.type == 2">服务商端</el-tag>
            <el-tag v-else type="info">仓库出入库端</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="页面标题" width="160" />
        <el-table-column show-overflow-tooltip prop="path" label="页面链接">
          <template #default="scope">
              <span class="link" style="flex: 1"> {{ scope.row.path }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="info">禁用</el-tag>
            <el-tag v-else>启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="150" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <div class="btns">
              <p class="bg_color2 copy" @click="copyPath" :data-clipboard-text="scope.row.path">复制链接</p>
              <span class="bg_color2" @click="getGenerate(scope.row)"
                v-show="!scope.row.status">二维码</span>
              <span class="bg_color2" @click="modifyClick(scope.row)">编辑</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination ref="pagination" :list_total="fieldTotal" @size-change="getList" @current-change="getList" />
    </div>
    </div>
  
  <!-- 修改  弹窗 -->
  <el-dialog v-model="addDialog" width="450px" :draggable="true" :destroy-on-close="true" :close-on-click-modal="false"
    class="add-dialog2" top="8vh">
    <template #header>
      <div class="my-header">
        <h3 class="title">{{ modifytitle }}</h3>
      </div>
    </template>
    <div v-loading="fieldLoading" element-loading-text="加载中...">
      <div class="form-text">
        <el-form label-width="85" ref="formRef" :rules="rules" :model="ruleForm">
          <el-form-item label="页面名称" class="form-item" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入页面名称" disabled />
          </el-form-item>
          <el-form-item label="类型" class="form-item" prop="type">
            <el-select v-model="ruleForm.type" disabled>
              <el-option v-for="(item, index) in pageTypeOption" :key="index" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="页面标题" class="form-item" prop="title">
            <el-input v-model="ruleForm.title" clearable placeholder="请输入页面标题" />
          </el-form-item>
          <el-form-item label="状态" class="form-item" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="false">
                <span class="bg_text">启用</span>
              </el-radio>
              <el-radio :label="true">
                <span class="bg_text">禁用</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="flex-justify-end">
        <div class="right">
          <el-button @click="addDialog = false" class="btn_cancel">取消</el-button>
          <el-button @click="saveData(formRef)" color="#007cff" class="btn_save">保存</el-button>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 二维码弹窗 -->
  <el-dialog v-model="qrDialog" :width="dataQr.pageIcons.length == 0 ? '700px' : '750px'" class="add-dialog2" top="8vh"
    draggable>
    <template #header>
      <div class="my-header">
        <h3 class="title">二维码详情</h3>
      </div>
    </template>
    <div class="qr-top">
      <el-row>
        <el-col :span="8">
          <span>页面类型：</span>
          <span class="qr-top-value" v-for="(item, index) in pageTypeOption" :key="index"
            v-show="item.value == qrPageState.type">
            {{ item.name }}</span>
        </el-col>
        <el-col :span="8">
          <span>页面名称：</span>
          <span class="qr-top-value">{{ qrPageState.name }}</span>
        </el-col>
        <el-col :span="8">
          <span>页面标题：</span>
          <span class="qr-top-value">{{ qrPageState.title }}</span>
        </el-col>
      </el-row>
    </div>
    <div class="big-gen" style="display: flex;" v-loading="qrLoading" element-loading-text="加载中...">
      <div class="gen-left">
        <div class="gen-left-1">
          <!-- 二维码标题 -->
          <div class="gen-title">
            <div class="gen-top" v-if="dataQr.qrStyleType !== 1"
              :style="dataQr.qrStyleType === 3 ? 'background:' + dataQr.qrBackgroundColor + '; color:' + dataQr.qrTextColor : ''">
              {{ dataQr.qrTitle }}
            </div>
          </div>
          <!-- 二维码 -->
          <div class="gen-center">
            <vue-qr :text="qrContentPath" :bindElement="true" :logoCornerRadius="0" :logoSrc="generateLogo"
              :logoMargin="7" id="qrcode"></vue-qr>
          </div>
          <div style="height: 20px">
            <!-- 二维码文案 -->
            <div class="gen-foot" v-show="dataQr.qrStyleType != 1">
              {{ dataQr.qrProgramme }}
            </div>
          </div>
        </div>

        <el-button class="gen-btn" @click="saveImg">
          <el-icon>
            <UploadFilled />
          </el-icon>下载二维码
        </el-button>
      </div>

      <div class="gen-right">
        <div class="qr-edit-title">二维码标题及样式编辑</div>
        <div style="height: 320px">
          <el-form ref="refDom" :rules="rules"  label-width="auto" :model="dataQr" label-positio="right">
            <div class="gen-right1">
              <div class="gen-right-l">图标</div>
              <el-form-item class="phone_add" style="flex: 1">
                <el-upload action="#" multiple list-type="picture-card" :show-file-list="false"
                  accept=".jpg,.png,.webp,.gif" :auto-upload="false" @change="getProImages" style="margin-left: 10px">
                  <div class="plus_add">
                    上传
                  </div>
                </el-upload>
                <template style="display: flex">
                  <span class="gen-span" v-for="(img, index) in dataQr.pageIcons" @click="selectImg(img, index)">
                    <div class="gen-img" :style="{ borderColor: img.select ? '#007cff' : '' }">
                      <el-image class="gen-image" :src="img.image"></el-image>
                      <div class="img-icon">
                        <el-icon class="img-icon-del" @click.stop="delImg(img, index)">
                          <Delete />
                        </el-icon>
                        <el-icon v-if="img.select" class="selecticon" color="#007cff">
                          <Check />
                        </el-icon>
                      </div>
                    </div>
                  </span>
                </template>
                <el-dialog v-model="dialogVisible" draggable top="8vh">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" class="img_view" />
                </el-dialog>
              </el-form-item>
            </div>

            <div class="gen-right2">
              <div class="gen-right-2">样式</div>
              <el-form-item v-model="dataQr.qrStyleType" size="large" style="margin: 20px 10px 0">
                <div class="gen-label label1" @click="handleChange1(1)"
                  :style="{ borderColor: dataQr.qrStyleType === 1 ? '#007cff' : '' }">
                  <div v-show="dataQr.qrStyleType === 1">
                    <el-icon class="gen-lable-icon" color="#007cff">
                      <Check />
                    </el-icon>
                  </div>
                </div>

                <div class="gen-label label2" @click="handleChange1(2)"
                  :style="{ borderColor: dataQr.qrStyleType === 2 ? '#007cff' : '' }">
                  <div class="hd">
                    <div v-show="dataQr.qrStyleType === 2">
                      <el-icon class="gen-lable-icon1" color="#007cff">
                        <Check />
                      </el-icon>
                    </div>
                  </div>
                  <div class="hd1"></div>
                </div>
                <div class="gen-label label3" @click="handleChange1(3)"
                  :style="{ borderColor: dataQr.qrStyleType === 3 ? '#007cff' : '' }">
                  <div class="hd"
                    :style="dataQr.qrStyleType === 3 ? 'background:' + dataQr.qrBackgroundColor + '; color:' + dataQr.qrTextColor : ''">
                    <div v-show="dataQr.qrStyleType === 3">
                      <el-icon class="gen-lable-icon1" color="#007cff">
                        <Check />
                      </el-icon>
                    </div>
                  </div>
                  <div class="hd1"></div>
                </div>
              </el-form-item>
            </div>

            <el-form-item label="标题" prop="qrTitle" class="el-qrTitle" v-show="dataQr.qrStyleType != 1">
              <el-input clearable placeholder="请输入标题" v-model="dataQr.qrTitle" maxlength="10" />
            </el-form-item>
            <el-form-item label="文案" prop="qrProgramme" class="el-qrTitle el-qrProgramme" v-show="dataQr.qrStyleType != 1"
              width="50px">
              <el-input clearable placeholder="请输入文案" v-model="dataQr.qrProgramme" maxlength="10" />
            </el-form-item>

            <el-form-item label="二维码标题字体颜色" class="el-color" v-show="dataQr.qrStyleType == 3">
              <el-color-picker v-model="dataQr.qrTextColor" :predefine="predefineColors" />
            </el-form-item>
            <el-form-item label="二维码标题背景颜色" class="el-color" v-show="dataQr.qrStyleType == 3">
              <el-color-picker v-model="dataQr.qrBackgroundColor" :predefine="predefineColors" />
            </el-form-item>
          </el-form>
        </div>
        <div class="flex-justify-between save-btn">
          <div class="right">
            <el-button @click="qrDialog = false" class="btn_cancel">取消</el-button>
            <el-button @click="SaveGenerate(refDom)" color="#007cff" class="btn_save">保存</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>

  </div>


</template>

<script setup lang="ts">
import { ref, reactive, onMounted, markRaw, watch } from 'vue'
import type { FormInstance, UploadFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Warning, Delete, Check, UploadFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import batch from '../../assets/image/batch.png'
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import html2canvas from 'html2canvas'
import { systemAcceUpload } from '../../api/upload'
import {
  getSyncService,
  getSyncList,
  getmodifyEmp,
  getgenerateInfo,
  getgeneratedata,
} from '../../api/servicepage'
import Clipboard from 'clipboard'

const tableLoading = ref(false) // 列表表格加载动画
const qrLoading = ref(false) // 二维码弹窗加载动画
const disabledBatchBtn = ref(true) // 批量操作按钮禁用状态
const tableData = ref([]) // 表格数据
const selecttion = ref([])// 表格选中的数据
const addDialog = ref(false)
const qrDialog = ref(false) // 二维码弹窗
const fieldLoading = ref(false) //加载指示器或进度条
const modifytitle = ref() //修改标题
const pagination = ref() // 分页dom
const tableDom = ref() //列表tom
const fieldTotal = ref() // 总数目
const fieldId = ref('') // 字段ID
const generateLogo = ref('') //二维码logo
const qrContentPath = ref('') // 二维码内容路径
const servicePageSearch = ref({
  page: 1,
  limit: 50,
  type: '', // 类型：1-客户报单端，2-服务商端，3-仓库出入库端
  name: '', // 页面名称
  title: '' // 页面标题
})
// 页面类型
const pageTypeOption = [
  {
    value: '1',
    name: '客户报单端',
  },
  {
    value: '2',
    name: '服务商端',
  },
  {
    value: '3',
    name: '仓库出入库端',
  },
]
// 页面类型
const qrPageState = reactive({
  type: '',
  name: '',
  title: ''
})

const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 表单元素
const formRef = ref()
const refDom = ref()
const ruleForm = reactive({
  id: null,
  name: '',
  type: null,
  title: '',
  status: false,
})
let dataQr:any = ref({
  delPageIconIds: [],
  id: null,
  pageIcons: [],
  qrProgramme: '',
  qrStyleType: 1,
  qrTitle: '',
  qrTextColor: '', //二维码标题颜色
  qrBackgroundColor: '', //二维码背景颜色
})

//选择二维码标题颜色
const qrTitleDefColor = ref('#FBFBFB') // 二维码标题默认颜色
const qrTitleBackgroundDefColor = ref('#007CFF') // 二维码标题背景默认颜色
// 预选颜色值
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
])
//验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  title: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  status: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  qrTitle: [{ required: true, message: '请输入标题', trigger: ['change', 'blur'] }],
})

//打开二维码弹窗（同时获取二维码详细数据）
const getGenerate = async (obj: any) => {
  qrDialog.value = true
  qrLoading.value = true
  fieldId.value = obj.id
  generateLogo.value = ''
  qrContentPath.value = ''
  await getgenerateInfo(fieldId.value).then((res) => {
    qrLoading.value = false
    if (res.data.code === 20000) {
      const data = res.data.data.row
      qrPageState.type = data.type
      qrPageState.name = data.name
      qrPageState.title = data.title
      qrContentPath.value = data.path
      dataQr.value = data
      dataQr.value.delPageIconIds = []
      if (dataQr.value.pageIcons) {
        generateLogo.value = dataQr.value.pageIcons.filter((f) => f.select)[0]?.image
      }
      if (!data.qrTextColor) {
        dataQr.value.qrTextColor = qrTitleDefColor.value
      }
      if (!data.qrBackgroundColor) {
        dataQr.value.qrBackgroundColor = qrTitleBackgroundDefColor.value
      }
    }
  })
}

//复制
const copyPath = () => {
  let clipboard = new Clipboard('.copy')
  clipboard.on('success', (e) => {
    ElMessage.success('复制成功')
    clipboard.destroy() // 释放内存
  })
  clipboard.on('error', (e) => {
    // 不支持复制
    ElMessage.warning('该浏览器不支持自动复制')
    clipboard.destroy() // 释放内存
  })
}
//获取服务页面列表
const getList = async () => {
  servicePageSearch.value.page = pagination.value.current
  servicePageSearch.value.limit = pagination.value.size
  tableLoading.value = true
  await getSyncList(servicePageSearch.value).then((res) => {
    tableLoading.value = false
    tableData.value = res.data.data.rows
    fieldTotal.value = parseInt(res.data.data.total)
  })
}

//同步服务
const syncclick = async () => {
  await getSyncService().then((resp) => {
    ElMessage({
      message: resp.data.message,
      type: resp.data.code !== 20000 ? 'error' : 'success',
      duration: 2000
    })
    if (resp.data.code === 20000) {
      getList()
    }
  })
}

//修改服务
const modifyClick = async (obj: any) => {
  addDialog.value = true
  modifytitle.value = '编辑服务'
  fieldId.value = obj.id
  ruleForm.title = obj.title
  ruleForm.name = obj.name
  ruleForm.type = obj.type
  ruleForm.status = obj.status
}

//封装服务页面数据
const EncapData = () => {
  const data = {
    id: fieldId.value,
    name: ruleForm.name,
    title: ruleForm.title,
    status: ruleForm.status,
    type: ruleForm.type,
  }
  fieldLoading.value = true
  getmodifyEmp(data).then((res) => {
    fieldLoading.value = false
    ElMessage({
      message: res.data.message,
      type: res.data.success ? 'success' : 'warning',
      duration: 2000,
    })
    if (res.data.success == true) {
      addDialog.value = false
      getList()
    }
  })
}

//保存服务页面数据
const saveData = (formEl) => {
  formEl.validate((valid) => {
    if (valid) {
      EncapData()
    }
  })
}

// 列表多选项框事件
const handleChange = (val: any[]) => {
  selecttion.value = []
  if (val.length > 0) {
    val.forEach((item) => {
      selecttion.value.push(item.id)
    })
  }
}

//批量操作方法
const changeMethod = (type, method, arr, status, dialog) => {
  if (arr.length == 0) {
    ElMessage({
      message: '请选择页面',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: type == '禁用' ? 'warning' : 'error',
    title: '提示',
    icon: type == '禁用' ? markRaw(Warning) : markRaw(Delete),
    message: `确认${type}选中的类型?`,
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    if (status != 3) {
      await method(arr, status).then((res: any) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      })
    } else {
      await method(arr).then((res: any) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        if (dialog != '') {
          dialog.value = false
        }
      })
    }
    tableDom.value.clearSelection()
    getList()
  })
}

// // 批量修改状态
// const changeAll = (n) => {
//   if (n == 1) {
//     changeMethod('启用', getBatchEnaDis, selecttion.value, false, '')
//   }
//   if (n == 2) {
//     changeMethod('禁用', getBatchEnaDis, selecttion.value, true, '')
//   }
// }

//上传图片 二维码logo
const getProImages = (uploadFile: UploadFile) => {
  if (dataQr.value.pageIcons.length >= 5) {
    ElMessage({
      message: '上传数量不能超过5张',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  dataQr.value.pageIcons.push({
    id: null,
    image: uploadFile.url,
    select: false,
    file: uploadFile.raw,
  })
}

// 删除图片
function delImg(img, index) {
  if (img.select == true) {
    generateLogo.value = ''
  }
  if (img.id) {
    dataQr.value.delPageIconIds.push(img.id)
  }
  dataQr.value.pageIcons = dataQr.value.pageIcons.filter((o, i) => {
    return i != index
  })
}
//选择图片
const selectImg = (img, index) => {
  dataQr.value.pageIcons = dataQr.value.pageIcons.map((o, i) => {
    if (index == i) {
      if (o.select == true) {
        generateLogo.value = ''
        return { ...o, select: false }
      } else {
        generateLogo.value = o.image
        return { ...o, select: true }
      }
    } else {
      return { ...o, select: false }
    }
  })
}

//样式监听
const handleChange1 = (newStyle: number) => {
  dataQr.value.qrStyleType = newStyle
}

//封装二维码数据
const EnGenerate = async () => {
  if (dataQr.value.pageIcons.length > 0) {
    for (let key = 0; key < dataQr.value.pageIcons.length; key++) {
      const imgObj = dataQr.value.pageIcons[key]
      if (imgObj.file) {
        let imgI = imgObj.file
        await systemAcceUpload([imgI]).then((res) => {
          if (res.data.success) {
            dataQr.value.pageIcons[key].image = res.data.data.rows[0]
            delete dataQr.value.pageIcons[key].file
          }
        })
      }
    }
  }
  qrLoading.value = true
  getgeneratedata(dataQr.value).then((res) => {
    qrLoading.value = false
    ElMessage({
      message: res.data.message,
      type: res.data.success ? 'success' : 'warning',
      duration: 2000,
    })
    if (res.data.success) {
      qrDialog.value = false
      getList()
    }
  })
}

//保存二维码数据
const SaveGenerate = (formEl: FormInstance | undefined) => {
  formEl.validate((valid) => {
    if (valid) {
      EnGenerate()
    }
  })
}

//下载二维码
const saveImg = () => {
  const dialogElement = document.querySelector('.gen-left-1') as HTMLElement // 显式断言为 HTMLElement 类型
  if (dialogElement) {
    html2canvas(dialogElement).then((canvas) => {
      const image = canvas.toDataURL('image/png')
      const a = document.createElement('a')
      a.href = image
      a.download = 'qr_code.png'
      a.click()
    })
  }
}

// 监听列表选中的数据
watch(
  () => selecttion.value,
  () => {
    disabledBatchBtn.value = true
    if (selecttion.value.length > 0) {
      disabledBatchBtn.value = false
    }
  }
)

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
@import './index.scss';

.qr-top {
  margin-bottom: 20px;
  color: #000000c9;

  .qr-top-value {
    color: #999999;
  }
}
</style>
